// PWA推送通知相关API
import express from 'express';
import { authenticateToken, optionalAuth } from '../middleware/auth'
import * as webpush from 'web-push';

const router = express.Router();

// VAPID密钥配置（生产环境应该从环境变量获取）
const vapidKeys = {
  publicKey: process.env.VAPID_PUBLIC_KEY || 'BCwA-MJHWcmZBteCFD2Am3oI5Hhcv9ORp8DKXLwYwSLB0yHCv4cOMwcse_DnFEKu9jXUwXMqKYtFtObQOyMmoVE',
  privateKey: process.env.VAPID_PRIVATE_KEY || 'fhEbXpAjVz7CeJXHfNlYm_sWST-Lb7s-qTwX7LX3Ep8'
};

// 配置web-push
webpush.setVapidDetails(
  'mailto:admin@aide.com',
  vapidKeys.publicKey,
  vapidKeys.privateKey
);

// 存储推送订阅的内存数据库（生产环境应该使用真实数据库）
const subscriptions = new Map<string, any>();

// 获取VAPID公钥
router.get('/vapid-public-key', (req, res) => {
  res.json({
    publicKey: vapidKeys.publicKey
  });
});

// 订阅推送通知（可选认证：若登录则绑定到用户，否则归属 anonymous）
router.post('/subscribe', optionalAuth, (req, res) => {
  try {
    const subscription = req.body;
    
    if (!subscription || !subscription.endpoint) {
      return res.status(400).json({
        error: '无效的订阅数据'
      });
    }

    // 存储订阅信息（实际应用中应该关联用户ID）
    const subscriptionId = Buffer.from(subscription.endpoint).toString('base64');
    subscriptions.set(subscriptionId, {
      ...subscription,
      userId: req.userId || 'anonymous',
      createdAt: new Date().toISOString()
    });

    console.log('新的推送订阅:', subscriptionId);

    res.json({
      success: true,
      subscriptionId
    });
  } catch (error) {
    console.error('订阅推送失败:', error);
    res.status(500).json({
      error: '订阅推送失败'
    });
  }
});

// 取消订阅推送通知
router.post('/unsubscribe', (req, res) => {
  try {
    const { endpoint } = req.body;
    
    if (!endpoint) {
      return res.status(400).json({
        error: '缺少endpoint参数'
      });
    }

    const subscriptionId = Buffer.from(endpoint).toString('base64');
    const deleted = subscriptions.delete(subscriptionId);

    console.log('取消推送订阅:', subscriptionId, deleted ? '成功' : '未找到');

    res.json({
      success: true,
      deleted
    });
  } catch (error) {
    console.error('取消订阅失败:', error);
    res.status(500).json({
      error: '取消订阅失败'
    });
  }
});

// 发送推送通知（需要认证；仅发送给当前登录用户的订阅）
router.post('/send', authenticateToken, async (req, res) => {
  try {
    const { title, body, data } = req.body;
    
    if (!title) {
      return res.status(400).json({
        error: '缺少通知标题'
      });
    }

    const payload = JSON.stringify({
      title,
      body: body || '',
      data: data || {},
      timestamp: Date.now()
    });

    const results = [];
    
    // 仅发送给当前登录用户的订阅
    for (const [subscriptionId, subscription] of subscriptions.entries()) {
      if (subscription.userId !== req.userId) {
        continue;
      }

      try {
        await webpush.sendNotification(subscription, payload);
        results.push({
          subscriptionId,
          status: 'sent'
        });
        console.log('推送通知发送成功:', subscriptionId);
      } catch (error) {
        console.error('推送通知发送失败:', subscriptionId, error);
        results.push({
          subscriptionId,
          status: 'failed',
          error: error instanceof Error ? error.message : String(error)
        });
        
        // 如果订阅已失效，删除它
        if (error && typeof error === 'object' && 'statusCode' in error && error.statusCode === 410) {
          subscriptions.delete(subscriptionId);
        }
      }
    }

    res.json({
      success: true,
      results,
      totalSent: results.filter(r => r.status === 'sent').length,
      totalFailed: results.filter(r => r.status === 'failed').length
    });
  } catch (error) {
    console.error('发送推送通知失败:', error);
    res.status(500).json({
      error: '发送推送通知失败'
    });
  }
});

// 获取订阅统计
router.get('/stats', (req, res) => {
  const stats: {
    totalSubscriptions: number;
    subscriptionsByUser: Record<string, number>;
  } = {
    totalSubscriptions: subscriptions.size,
    subscriptionsByUser: {}
  };

  for (const [subscriptionId, subscription] of subscriptions.entries()) {
    const userId = subscription.userId;
    if (!stats.subscriptionsByUser[userId]) {
      stats.subscriptionsByUser[userId] = 0;
    }
    stats.subscriptionsByUser[userId]++;
  }

  res.json(stats);
});

// 测试推送通知
router.post('/test', async (req, res) => {
  try {
    const payload = JSON.stringify({
      title: '🔔 测试推送通知',
      body: '这是一个来自服务器的测试推送通知',
      data: {
        test: true,
        timestamp: Date.now(),
        url: '/'
      }
    });

    const results = [];
    
    // 发送给所有订阅用户
    for (const [subscriptionId, subscription] of subscriptions.entries()) {
      try {
        await webpush.sendNotification(subscription, payload);
        results.push({
          subscriptionId,
          status: 'sent'
        });
      } catch (error) {
        console.error('测试推送失败:', subscriptionId, error);
        results.push({
          subscriptionId,
          status: 'failed',
          error: error instanceof Error ? error.message : String(error)
        });
        
        // 如果订阅已失效，删除它
        if (error && typeof error === 'object' && 'statusCode' in error && error.statusCode === 410) {
          subscriptions.delete(subscriptionId);
        }
      }
    }

    res.json({
      success: true,
      message: '测试推送已发送',
      results,
      totalSent: results.filter(r => r.status === 'sent').length,
      totalFailed: results.filter(r => r.status === 'failed').length
    });
  } catch (error) {
    console.error('发送测试推送失败:', error);
    res.status(500).json({
      error: '发送测试推送失败'
    });
  }
});

export default router;
